package com.test.realcityalfa.connection;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import com.test.realcityalfa.exception.InternetConnectionException;
import com.test.realcityalfa.exception.NoInternetConnectionException;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class InternetConnection
{
	ResponseHandler<String> handler = new BasicResponseHandler();	
	int requestMethodId;
	String jsonData;
	
	public InternetConnection(int requestMethodId)
	{
		this.requestMethodId = requestMethodId;
	}
	
	public void setRequestData(String jsonData)
	{
		this.jsonData = jsonData;
	}
	
	public String execute() throws InternetConnectionException
	{
		if(RequestMethodFactory.GET_METHOD == requestMethodId)
		{
			GetRequestMethod method = (GetRequestMethod) RequestMethodFactory.getRequestFactory(requestMethodId);
			
			HttpGet _httpMethod = (HttpGet) method.getHttpMethod(jsonData);
			//Log.d("TEST", _httpMethod.getURI().toString());
			HttpClient _httpClient = new DefaultHttpClient();

			try
			{
				return _httpClient.execute(_httpMethod, handler);				
			}
			catch(Exception ex)
			{
				Logger.getLogger(InternetConnection.class.getName()).log(Level.SEVERE, null, ex);
				throw new InternetConnectionException("Error while performing request", ex);
			}
			
		}
		return new String();
	}
	
	public boolean isConnectionAvailable(Activity activity) throws NoInternetConnectionException
	{
		ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if(netInfo != null && netInfo.isConnectedOrConnecting())
		{
			Log.d("InternetConnection", "Info: " + netInfo.getType());
			return true;
		}
		
		throw new NoInternetConnectionException("No connected or connecting network with access to internet.");
	}

}
